#include <QSettings>
#include <QDebug>
#include "Browse.h"


BrowsePlugin::BrowsePlugin()// addImagePluginStratum *Stratum )
	: QObject()//, addImagePluginClass(Stratum)
{
	About.Name          = "Browse";
	About.Description   = "Just Browse Images";
	About.Author        = "Name_No (Nick Malakhov)";
	About.email         = "nomen.infitior@gmail.com";
	About.version       = "0.1";
	About.icon.addPixmap(QPixmap(QString::fromUtf8(":/Icons/document-open.png")), QIcon::Normal, QIcon::Off);
	Config = new QSettings();
	Config->beginGroup("BrowsePlugin");
	
}


void BrowsePlugin::setStratum(addImagePluginStratum *Stratum)
{
	this->Stratum = Stratum;
	connect(this, SIGNAL(addMyWidget(QWidget*)), this->Stratum, SIGNAL(addMyWidget(QWidget*)));
	connect(this, SIGNAL(addImage(QString)), this->Stratum, SIGNAL(addImage(QString)));
	stratumApeared();
}

void BrowsePlugin::stratumApeared()
{
	myForm = new QWidget();
	ui.setupUi(myForm);
	connect(ui.BrowseButton, SIGNAL(clicked()), this, SLOT(browseButtonClicked()));
	connect(ui.insertButton, SIGNAL(clicked()), this, SLOT(addFromLineEdit()));
	emit addMyWidget(myForm);
}

void BrowsePlugin::browseButtonClicked()
{

	QFileDialog *openFiles = new QFileDialog();
	openFiles->setFilter(tr("Images(*.png *.jpg *.xpm *.gif *.bmp);;All(*)"));
	openFiles->setFileMode(QFileDialog::ExistingFiles);
	if ( ! openFiles->restoreState(Config->value("browseWindow").toByteArray()) )
	{
		QString path = QDir::homePath();
		openFiles->setDirectory(path);
	} else {
		openFiles->setDirectory(Config->value("browseWindowPath").toString());
	}
	if (openFiles->exec()) {
		QStringList files = openFiles->selectedFiles();
		foreach (QString file, files) {
			if ( checkImageValid(file) )
				emit addImage(file);
		}
	}
	Config->setValue("browseWindow", openFiles->saveState());
	Config->setValue("browseWindowPath", openFiles->directory().path());
}

bool BrowsePlugin::checkImageValid(QString fileName)
{
	qDebug() << "check imageValid:" << fileName;
	// TODO: guess what?
	return true;
}


void BrowsePlugin::addFromLineEdit()
{
	if ( checkImageValid(ui.lineEdit->text()) ){
		emit addImage(ui.lineEdit->text());
	}
}

Q_EXPORT_PLUGIN2(WTFIcanWriteHere, BrowsePlugin);
